package com.gaojinqi.lock.controller;

import com.gaojinqi.lock.IDistributedLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author gaojinqi
 * @version 1.0
 * @since 2020年07月7日
 */
@RestController
public class SeckillController {

    ExecutorService executorService = Executors.newFixedThreadPool(20000);

    @Autowired
    private IDistributedLock distributedLock;

    private static Integer TICKET = 200;
    private static Integer PURCHASED = 0;

    public void buy() {
        String key = "ticket";
        boolean acquired = distributedLock.lock(key, 1000, TimeUnit.MILLISECONDS, 1000000);
        if (!acquired) {
            return;
        }
        if (TICKET <= 0) {
            throw new RuntimeException("票购买完啦，当前剩余票数：" + TICKET + "， 已卖：" + PURCHASED);
            // return;
        }
        try {
            TICKET--;
            PURCHASED++;
            System.out.println("当前剩余票数：" + TICKET + "， 已卖：" + PURCHASED);
            Thread.sleep(500);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            distributedLock.unlock(key);
        }
    }

    @RequestMapping("/testRedisLock")
    public String test() {
        for (int i = 0; i < 201; i++) {

            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            executorService.execute(this::buy);
        }
        return "success";
    }

}
